package com.bnyy.medicalHousekeeper.moudle.health.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAChartModel;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAChartView;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAMoveOverEventMessageModel;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AASeriesElement;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartAlignType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartLineDashStyleType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartStackingType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartSymbolStyleType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartSymbolType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartVerticalAlignType;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AACrosshair;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAMarker;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAOptions;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AASeries;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AASeriesEvents;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAStyle;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AATooltip;
import com.bnyy.common.view.AAChartCoreLib.AATools.AAColor;
import com.bnyy.common.view.AAChartCoreLib.AATools.AAGradientColor;
import com.bnyy.common.view.AAChartCoreLib.AATools.AALinearGradientDirection;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.gbp.customsView.circleprogress.CircleProgress;
import com.bnyy.health.bean.BloodPressureRange;
import com.bnyy.health.bean.BloodPressureWeekly;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseFragmentImpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import butterknife.BindView;
import me.gujun.android.taggroup.TagGroup;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/8/26
 **/
public class BloodPressureWeeklyFragment extends BaseFragmentImpl {

    @BindView(R.id.iv_expert)
    ScaleImageView ivExpert;
    @BindView(R.id.tv_expert)
    TextView tvExpert;
    @BindView(R.id.tag_group)
    TagGroup tagGroup;
    @BindView(R.id.tv_expert_desc)
    TextView tvExpertDesc;
    @BindView(R.id.tv_suggestion)
    TextView tvSuggestion;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_high)
    TextView tvHigh;
    @BindView(R.id.tv_normal_high)
    TextView tvNormalHigh;
    @BindView(R.id.tv_normal)
    TextView tvNormal;
    @BindView(R.id.tv_low)
    TextView tvLow;
    @BindView(R.id.aa_chart_view_trend)
    AAChartView aaChartViewTrend;
    @BindView(R.id.aa_chart_view_range)
    AAChartView aaChartViewRange;
    @BindView(R.id.tv_high_max)
    TextView tvHighMax;
    @BindView(R.id.tv_high_max_time)
    TextView tvHighMaxTime;
    @BindView(R.id.tv_high_min)
    TextView tvHighMin;
    @BindView(R.id.tv_high_min_time)
    TextView tvHighMinTime;
    @BindView(R.id.tv_low_max)
    TextView tvLowMax;
    @BindView(R.id.tv_low_max_time)
    TextView tvLowMaxTime;
    @BindView(R.id.tv_low_min)
    TextView tvLowMin;
    @BindView(R.id.tv_low_min_time)
    TextView tvLowMinTime;
    @BindView(R.id.tv_more_than_day)
    TextView tvMoreThanDay;
    @BindView(R.id.tv_more_than_day_count)
    TextView tvMoreThanDayCount;
    @BindView(R.id.tv_lower_than_day)
    TextView tvLowerThanDay;
    @BindView(R.id.tv_lower_than_day_count)
    TextView tvLowerThanDayCount;
    @BindView(R.id.tv_more_than_night)
    TextView tvMoreThanNight;
    @BindView(R.id.tv_more_than_night_count)
    TextView tvMoreThanNightCount;
    @BindView(R.id.tv_lower_than_night)
    TextView tvLowerThanNight;
    @BindView(R.id.tv_lower_than_night_count)
    TextView tvLowerThanNightCount;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_qrcode)
    ScaleImageView ivQrcode;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.circle_progress_bar)
    CircleProgress circleProgressBar;

    private Callback callback;

    public static BloodPressureWeeklyFragment getInstance(BloodPressureWeekly bloodPressureWeekly, boolean share) {
        BloodPressureWeeklyFragment fragment = new BloodPressureWeeklyFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("bloodPressureWeekly", bloodPressureWeekly);
        bundle.putBoolean("share", share);
        fragment.setArguments(bundle);
        return fragment;
    }

    public interface Callback {
        /**
         * 更新周报
         *
         * @param consumer
         */
        void onUpdate(Consumer<BloodPressureWeekly> consumer);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_health_blood_pressure_weekly;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Callback) {
            callback = (Callback) context;
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle arguments = getArguments();
        BloodPressureWeekly bloodPressureWeekly = (BloodPressureWeekly) arguments.getSerializable("bloodPressureWeekly");

        tvUpdate.setVisibility(bloodPressureWeekly.isReadOnly() ? View.GONE : View.VISIBLE);

        AAChartView.AAChartViewCallBack aaChartViewCallBack = new AAChartView.AAChartViewCallBack() {
            @Override
            public void chartViewDidFinishLoad(AAChartView aaChartView) {
            }

            @Override
            public void chartViewMoveOverEventMessage(AAChartView aaChartView, AAMoveOverEventMessageModel messageModel) {

            }
        };
        aaChartViewTrend.callBack = aaChartViewCallBack;
        aaChartViewRange.callBack = aaChartViewCallBack;

        boolean share = arguments.getBoolean("share", false);
        if (share) {
            tvUpdate.setVisibility(View.GONE);
            tvWx.setVisibility(View.VISIBLE);
            tvWx.setText(bloodPressureWeekly.getOfficial_title());
            ivQrcode.setVisibility(View.VISIBLE);
            GlideHelper.setImage(mContext, bloodPressureWeekly.getOfficial_qrcode(), ivQrcode);
        } else {
            tvUpdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onUpdate(new Consumer<BloodPressureWeekly>() {
                        @Override
                        public void accept(BloodPressureWeekly bloodPressureWeekly) {
                            setWeekly(bloodPressureWeekly);
                        }
                    });
                }
            });
        }

        setWeekly(bloodPressureWeekly);
    }

    private void setWeekly(BloodPressureWeekly weekly) {
        BloodPressureWeekly.Detail detail = weekly.getHwr_detail();
        setStats(detail.getGeneral_info());
        setRanges(detail.getDay_scope());
        setTrends(detail.getDay_trend());
        setWarnDetail(detail.getBlood_press_warn());
        setExpert(detail.getDoctor_info());
        setBloodPressureMaxAndMin(detail.getBlood_press_range());
    }

    private void setStats(BloodPressureWeekly.Detail.Stats stats) {

        if (stats == null) {
            return;
        }

        circleProgressBar.setValue(stats.getGrade());

        tvCount.setText("本周一共检测" + stats.getCount() + "次血压");
        SpanUtils.with(tvHigh)
                .append(stats.getHigh_count() + "").setFontSize(18, true).setForegroundColor(Color.parseColor("#FE8925")).setBold()
                .appendLine()
                .append("高危")
                .create();

        SpanUtils.with(tvNormalHigh)
                .append(stats.getSide_high_count() + "").setFontSize(18, true).setForegroundColor(Color.parseColor("#72CB52")).setBold()
                .appendLine()
                .append("正常偏高")
                .create();

        SpanUtils.with(tvNormal)
                .append(stats.getNormal_count() + "").setFontSize(18, true).setForegroundColor(Color.parseColor("#0CCAAB")).setBold()
                .appendLine()
                .append("正常")
                .create();

        SpanUtils.with(tvLow)
                .append(stats.getNormal_count() + "").setFontSize(18, true).setForegroundColor(Color.parseColor("#CECECE")).setBold()
                .appendLine()
                .append("偏低")
                .create();
    }

    private void setBloodPressureMaxAndMin(BloodPressureWeekly.Detail.BloodPressureMaxAndMin maxAndMin) {

        if (maxAndMin == null) {
            return;
        }

        SimpleDateFormat sdfYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfMDHM = new SimpleDateFormat("MM-dd HH:mm");

        BloodPressureRange high = maxAndMin.getHigh();

        tvHighMax.setText("最高收缩压" + high.getMax() + "mmHg");

        if (!TextUtils.isEmpty(high.getMax_dt())) {
            try {
                tvHighMaxTime.setText(sdfMDHM.format(sdfYMDHMS.parse(high.getMax_dt())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        tvHighMin.setText("最低收缩压" + high.getMin() + "mmHg");
        if (!TextUtils.isEmpty(high.getMin_dt())) {
            try {
                tvHighMinTime.setText(sdfMDHM.format(sdfYMDHMS.parse(high.getMin_dt())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        BloodPressureRange low = maxAndMin.getLow();

        tvLowMax.setText("最高舒张压" + low.getMax() + "mmHg");
        if (!TextUtils.isEmpty(low.getMax_dt())) {
            try {
                tvLowMaxTime.setText(sdfMDHM.format(sdfYMDHMS.parse(low.getMax_dt())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        tvLowMin.setText("最低舒张压" + low.getMin() + "mmHg");
        if (!TextUtils.isEmpty(low.getMin_dt())) {
            try {
                tvLowMinTime.setText(sdfMDHM.format(sdfYMDHMS.parse(low.getMin_dt())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private void setWarnDetail(BloodPressureWeekly.Detail.WarnDetail warnDetail) {
        int grayText = ContextCompat.getColor(mContext, R.color.gray_text);

        BloodPressureWeekly.Detail.WarnDetail.When day = warnDetail.getDaytime();
        BloodPressureWeekly.Detail.WarnDetail.When.Element dayMoreThan = day.getHigh();
        tvMoreThanDay.setText(dayMoreThan.getDesc());
        tvMoreThanDayCount.setText(dayMoreThan.getCount() + "次");
        if (dayMoreThan.getCount() > 0) {
            tvMoreThanDayCount.setTextColor(grayText);
        }
        BloodPressureWeekly.Detail.WarnDetail.When.Element dayLowerThan = day.getLow();
        tvLowerThanDay.setText(dayLowerThan.getDesc());
        tvLowerThanDayCount.setText(dayLowerThan.getCount() + "次");
        if (dayLowerThan.getCount() > 0) {
            tvLowerThanDayCount.setTextColor(grayText);
        }

        BloodPressureWeekly.Detail.WarnDetail.When night = warnDetail.getNight();
        BloodPressureWeekly.Detail.WarnDetail.When.Element nightMoreThan = night.getHigh();
        tvMoreThanNight.setText(nightMoreThan.getDesc());
        tvMoreThanNightCount.setText(nightMoreThan.getCount() + "次");
        if (nightMoreThan.getCount() > 0) {
            tvMoreThanNightCount.setTextColor(grayText);
        }
        BloodPressureWeekly.Detail.WarnDetail.When.Element nightLowerThan = night.getLow();
        tvLowerThanNight.setText(nightLowerThan.getDesc());
        tvLowerThanNightCount.setText(nightLowerThan.getCount() + "次");
        if (nightLowerThan.getCount() > 0) {
            tvLowerThanNightCount.setTextColor(grayText);
        }
    }

    private void setExpert(BloodPressureWeekly.Detail.DoctorInfo expert) {
        if (expert == null) {
            return;
        }

        if (!TextUtils.isEmpty(expert.getImg())) {
            GlideHelper.setCircleImage(mContext, expert.getImg(), ivExpert);
        }
        ArrayList<String> tags = expert.getTags();
        if (tags != null && tags.size() > 0) {
            tagGroup.setTags(tags);
        }
        tvExpert.setText(expert.getName());
        tvExpertDesc.setText(expert.getBrief());
        tvSuggestion.setText(expert.getContent());
    }

    private void setTrends(ArrayList<BloodPressureWeekly.Detail.Trend> trends) {
        SimpleDateFormat sdfYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfMD = new SimpleDateFormat("MM-dd");
        int size = trends.size();
        Object[] high = new Object[size];
        Object[] low = new Object[size];
        String[] categories = new String[size];

        for (int i = 0; i < size; i++) {
            BloodPressureWeekly.Detail.Trend trend = trends.get(i);

            high[i] = trend.getHigh_value() > 0 ? trend.getHigh_value() : null;
            low[i] = trend.getLow_value() > 0 ? trend.getLow_value() : null;
            try {
                categories[i] = sdfMD.format(sdfYMDHMS.parse(trend.getCreate_datetime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

//        medicationElement.y(max + 10);

        Map<String, Object> gradientGreenColorDicHight = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToBottom,
                new Object[][]{
                        {0.0, AAColor.rgbaColor(255, 164, 76, 0.6f)},//颜色字符串设置支持十六进制类型和 rgba 类型
                        {0.5, AAColor.rgbaColor(255, 164, 76, 0.3f)},
                        {1.0, AAColor.rgbaColor(255, 164, 76, 0.0f)}
                }
        );

        Map<String, Object> gradientGreenColorDicLow = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToBottom,
                new Object[][]{
                        {0.0, AAColor.rgbaColor(241, 210, 0, 0.6f)},//颜色字符串设置支持十六进制类型和 rgba 类型
                        {0.5, AAColor.rgbaColor(241, 210, 0, 0.3f)},
                        {1.0, AAColor.rgbaColor(241, 210, 0, 0.0f)}
                }
        );

        AAChartModel aaChartModel = new AAChartModel()
                .dataLabelsEnabled(false)//是否显示值
                .categories(categories)
                .xAxisLabelsEnabled(true)
                .touchEventEnabled(true)
                .stacking(AAChartStackingType.Normal)
                .yAxisVisible(true)
                .markerSymbolStyle(AAChartSymbolStyleType.InnerBlank)
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("高压")
                                .type(AAChartType.Areaspline)
                                .lineWidth(1.5f)
                                .marker(new AAMarker()
                                        .symbol(AAChartSymbolType.Circle)
                                )
                                .color("#FFA44C")
                                .fillColor(gradientGreenColorDicHight)
                                .data(high),
                        new AASeriesElement()
                                .name("低压")
                                .type(AAChartType.Areaspline)
                                .lineWidth(1.5f)
                                .color("#F1D200")
                                .marker(new AAMarker()
                                        .symbol(AAChartSymbolType.Circle))
                                .fillColor(gradientGreenColorDicLow)
                                .data(low),
                });

        AAOptions aaOptions = aaChartModel.aa_toAAOptions();
        aaOptions.legend.verticalAlign(AAChartVerticalAlignType.Top);
        aaOptions.legend.align(AAChartAlignType.Center);

        aaOptions.plotOptions.series(new AASeries()
                .connectNulls(true)
                .events(new AASeriesEvents()
                        .legendItemClick(" function () {" +
                                "return false;" +
                                "}"))
        );
        aaChartViewTrend.aa_drawChartWithChartOptions(aaOptions);
    }

    private void setRanges(ArrayList<BloodPressureWeekly.Detail.Range> ranges) {
        SimpleDateFormat sdfMD = new SimpleDateFormat("MM-dd");
        SimpleDateFormat sdfYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int size = ranges.size();
        Object[] high = new Object[size];
        Object[] low = new Object[size];
        String[] categories = new String[size];

        int max = 0, min = 0;

        for (int i = 0; i < size; i++) {
            BloodPressureWeekly.Detail.Range range = ranges.get(i);
            try {
                categories[i] = sdfMD.format(sdfYMDHMS.parse(range.getCreate_datetime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            BloodPressureRange rangeHigh = range.getHigh();
            int rangeHighMax = rangeHigh.getMax();
            int rangeHighMin = rangeHigh.getMin();

            HashMap<String, Object> paramsHigh = new HashMap<>();
            paramsHigh.put("showHigh", rangeHighMax);
            paramsHigh.put("showLow", rangeHighMin);

            if (rangeHighMax > 0 && rangeHighMin > 0) {
                if (rangeHighMax - rangeHighMin < 10) {
                    rangeHighMax += (10 - (rangeHighMax - rangeHighMin));
                }
                paramsHigh.put("high", rangeHighMax);
                paramsHigh.put("low", rangeHighMin);
            } else {
                paramsHigh.put("high", null);
                paramsHigh.put("low", null);
            }

            high[i] = paramsHigh;

            if (rangeHighMax > max) {
                max = rangeHighMax;
            }
//            high[i] = new Object[]{rangeHighMax, rangeHighMin};
            BloodPressureRange rangeLow = range.getLow();
            int rangeLowMax = rangeLow.getMax();
            int rangeLowMin = rangeLow.getMin();

            HashMap<String, Object> paramsLow = new HashMap<>();
            paramsLow.put("showHigh", rangeLowMax);
            paramsLow.put("showLow", rangeLowMin);

            if (rangeLowMax > 0 && rangeLowMin > 0) {
                if (rangeLowMax - rangeLowMin < 10) {
                    rangeLowMax += (10 - (rangeLowMax - rangeLowMin));
                }
                paramsLow.put("high", rangeLowMax);
                paramsLow.put("low", rangeLowMin);
                if (min == 0 || min > rangeLowMin) {
                    min = rangeLowMin;
                }
            } else {
                paramsLow.put("high", null);
                paramsLow.put("low", null);
            }

            low[i] = paramsLow;
        }

        AASeriesElement[] aaSeriesElements;
        aaSeriesElements = new AASeriesElement[]{
                new AASeriesElement()
                        .name("高压")
                        .color("#FFA44C")
                        .data(high),
                new AASeriesElement()
                        .name("低压")
                        .color("#F1D200")
                        .data(low),
        };

        AAChartModel aaChartModel = new AAChartModel()
                .chartType(AAChartType.Columnrange)
                .dataLabelsEnabled(false)//是否显示值
                .categories(categories)
                .xAxisLabelsEnabled(true)
                .touchEventEnabled(true)
                .markerRadius(0f)
//                .legendEnabled(false)
                .stacking(AAChartStackingType.Normal)
                .series(aaSeriesElements);
        AAOptions aaOptions = aaChartModel.aa_toAAOptions();

        Object[] y = new Object[4];
        max += 10;
        min -= 10;
        int d = ((max + 10) - (min - 10)) / 4;
        for (int i = 0; i < y.length; i++) {
            if (i == y.length - 1) {
                y[i] = max;
            } else {
                y[i] = min + (d * i);
            }
        }

        aaOptions.yAxis.tickPositions(y)
                .gridLineDashStyle(AAColor.rgbaColor(244, 244, 244, 0.8f))
                .gridLineWidth(0.5f);

        aaOptions.plotOptions.columnrange.borderRadius(5f);

        // 点击线
        aaOptions.xAxis.crosshair(new AACrosshair()
                .color(AAColor.rgbaColor(255, 241, 228, 0.7f))
//                .width(high.length == 7 ? 20f : 10f)
                .dashStyle(AAChartLineDashStyleType.Solid));

        AATooltip aaTooltip = new AATooltip();
        aaTooltip.style(new AAStyle()
                .fontSize(10)
                .padding(0))
                .formatter("function () {" +
                        "let myPointOptions = this.points[0].point.options;" +
                        "let myPointOptions1 = this.points[1].point.options;" +
                        "let s = this.x + '<br/>';" +
                        "let colorDot1 = '<span style=\\\"' + 'color:#FFA44C; font-size:8px\\\"' + '>●</span> ';" +
                        "let colorDot2 = '<span style=\\\"' + 'color:#F1D200; font-size:8px\\\"' + '>●</span> ';" +
                        "let s1 = colorDot1 + this.points[0].series.name + ': ' + myPointOptions.showHigh + '-' + myPointOptions.showLow;" +
                        "let s2 = colorDot2 + this.points[1].series.name + ': ' + myPointOptions1.showHigh + '-' + myPointOptions1.showLow;" +
                        "s += s1 + '<br/>' + s2 ;" +
                        "return s;" +
                        "}")
                .valueDecimals(2);//设置取值精确到小数点后几位//设置取值精确到小数点后几位
        aaOptions.tooltip(aaTooltip);

        aaOptions.plotOptions.series.connectNulls(true)
                .events(new AASeriesEvents()
                        .legendItemClick(" function () {" +
                                "return false;" +
                                "}"));
        aaOptions.legend.verticalAlign(AAChartVerticalAlignType.Top)
                .align(AAChartAlignType.Center);

        aaChartViewRange.aa_drawChartWithChartOptions(aaOptions);
    }
}





























